var pool = require('../modules/db_mysql').pool;

module.exports.save = function save(data, callback) {
    pool.getConnection(function(err, connection) {
        var sql = "";
        if(data.id == 0){
            sql ="insert into tag (`title`, `color`, `status`, `order`, `last_modified_time`) values "
                + "(?,?, 1, 50, now())";
        }else{
            sql = "update tag "
                + " set title=?, color=?, last_modified_time=now() "            
                + " where id="+data.id
        }
        connection.query(sql, [data.title, data.color],function(err, result, fields){
            connection.release();
            if (err) {
                callback(err);
            } else {
                //返回用户id
                if(data.id == 0){
                    data.id = result.insertId;
                }

                return callback(err, data.id);
            }
        });
    });
};


module.exports.search = function search(condition, callback) {
    condition.findOne = condition.findOne || false;
    condition.searchType = condition.searchType || 0;  //0 only view
    var selectSql = "";

    if(condition.searchType == 0){
        selectSql = "select t.id, t.title, t.color "
            + "from tag t ";
    }
    else{
        selectSql = "select t.id, t.title, t.color, count(e.id) as count "
            + "from tag t "
            + "left join essay_tag et on t.id=et.tag_id "
            + "left join essay e on et.essay_id=e.id and e.status=1 "
            
        //+ "where c.name='"+username+"'";
    }
    var whereSql = "";
    if(condition.searchCriteria && condition.searchCriteria.id != 0){
        whereSql += " where t.id=" + condition.searchCriteria.id
    }
    var groupSql = " group by t.id desc";
    var sql = selectSql + whereSql + groupSql;
    console.log("Tag.search:", sql);

    pool.getConnection(function(err, connection) {
        connection.query(sql, function(err, result, fields){
            connection.release();
            if(err){
                callback(err);
            }else{
                console.log("result:", result.length);
                //console.log("fields:", fields);
                callback(err, result);
            }
        });
    });

};